package com.hdmp.auth.aspect;

import com.hdmp.auth.entity.SysUserEntity;
import com.hdmp.auth.service.DataAuthService;
import com.hdmp.auth.service.SysOrgService;
import com.hdmp.auth.service.SysUserService;
import com.hdmp.auth.shiro.ShiroUser;
import com.hdmp.mybatis.constant.DatabaseFieldConstant;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author BigFan
 * @create 2018/11/18 1:24 PM
 */
@Aspect
@Component
public class DataPermissionAspect {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    DataAuthService dataAuthService;

    @Pointcut("@annotation(com.hdmp.auth.aspect.DataPermission)")
    public void pointCut() {

    }


    @Before("pointCut()")
    public void permissionFilter(JoinPoint point) {
        Object params = point.getArgs();
        if (params != null && params instanceof Math) {
            ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
            SysUserEntity sysUserEntity = sysUserService.loadByBdid(shiroUser.getId());
            if (!sysUserEntity.getSuperUser()) {
                Map map = (Map)params;
                MethodSignature signature = (MethodSignature) point.getSignature();
                DataPermission dataPermission = signature.getMethod().getAnnotation(DataPermission.class);
                String dataSql = dataAuthService.createDataSql(sysUserEntity,dataPermission);
                map.put(DatabaseFieldConstant.DATA_FILTER_SQL,dataSql);

            }

        }
    }


}
